﻿<template>
    <div class="csRecord-container">
        <el-card shadow="hover">
            <el-form :model="state.queryParams" ref="queryForm" :inline="true">
                <el-form-item :label-width='70' label="手机号码" prop="phone">
                    <el-input placeholder="手机号码" clearable class='ml10' @keyup.enter="handleQuery"
                              v-model="state.queryParams.phone"/>
                </el-form-item>
                <el-form-item :label-width='70' label='日期'>
                    <el-date-picker class='ml10' v-model='state.queryParams.dateRange' type='daterange'
                                    inputmode="none"
                                    :shortcuts="selectShortcuts"
                                    placeholder='日期'
                                    date-format="YYYY/MM/DD" value-format="YYYY-MM-DD"
                                    :disabled-date="disableFutureDates"
                                    range-separator='至' start-placeholder='开始日期' end-placeholder='结束日期'
                                    :picker-options="{firstDayOfWeek: 1 }"
                                    :clearable="false"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button-group>
                        <el-button type="primary" icon="ele-Search" @click="handleQuery" :loading="state.loading"
                                   v-auth="'csRecord:query'">
                            查询
                        </el-button>
                        <el-button icon="ele-Refresh" @click="resetQuery" v-auth="'csRecord:query'"> 重置
                        </el-button>
                    </el-button-group>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card shadow="hover" style="margin-top: 8px">
            <el-table :data="state.data" style="width: 100%" v-loading="state.loading" tooltip-effect="light"
                      row-key="id" border stripe highlight-current-row @cell-mouse-enter="TransferIn"
                      @cell-mouse-leave="mark">
                <el-table-column header-align="center" prop="productName" label="产品名称" min-width="180"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="phoneC" width="115" label="手机号码" align="center"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="province" width="82" label="省份" align="center"
                                 show-overflow-tooltip/>
                <el-table-column header-align="center" prop="channelChargingResponse" min-width="160" label="计费响应"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        <el-text
                            :type='scope.row.channelChargingResponse?.indexOf(":\"0000\"") == -1 ? "danger" : "success"'>
                            {{
                                scope.row.channelChargingResponse
                            }}
                        </el-text>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="channelVerifyResponse" min-width="160" label="验证响应"
                                 show-overflow-tooltip>
                    <template #default="scope">
                        <el-text
                            :type='scope.row.channelVerifyResponse?.indexOf(":\"0000\"") == -1 ? scope.row.orderStatus === 1 ? "success" : "danger" : "success"'>
                            {{
                                scope.row.channelVerifyResponse
                            }}
                        </el-text>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="channelVerifyCode" width="80" label="验证码" align="right"
                                 show-overflow-tooltip/>
                <el-table-column header-align='center' label="订单状态" align="center" show-overflow-tooltip width="82">
                    <template #default="scope">
                        <template v-if="scope.row.channelVerifyCode">
                            <el-tag type="success" v-if="scope.row.orderStatus === 1">成功</el-tag>
                            <el-tag type="warning" v-else-if="scope.row.orderStatus === 2">处理中</el-tag>
                            <el-tag type="danger" v-else-if="scope.row.orderStatus === 3">失败</el-tag>
                            <el-tag type="warning" v-else-if="scope.row.orderStatus === 4">退订</el-tag>
                            <el-tag type="warning" v-else>未知</el-tag>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="createTime" width="160" label="请求时间"
                                 show-overflow-tooltip/>
                <el-table-column label="操作" width="60" align="center" fixed="right" show-overflow-tooltip>
                    <template #default="scope">
                        <el-button size="small" text type="primary" @click="openEditEsSmsInteraction(scope.row)"
                                   v-auth="'csRecord:detail'">详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" class="mt15"
                           :page-sizes="[20, 50, 100]" v-model:current-page="state.queryParams.pageNum" background
                           v-model:page-size="state.queryParams.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="state.total"/>
            <EditCsRecord ref="editCsRecordRef" :title="state.editTitle"/>
        </el-card>
    </div>
</template>

<script lang="ts" setup name="csRecord">

import {onMounted, onUnmounted, reactive, ref} from 'vue';
import mittBus from '/@/utils/mitt';
import EditCsRecord from '/@/views/cs/record/component/editCsRecord.vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {selectShortcuts, disableFutureDates, todayDate} from '/@/utils/dateHelper';
import {EsSmsInteraction, sysBaseDict} from '/@/api/models';
import SysEsSmsInteractionApi from '/@/api/exocytosis/smsInteraction';
import {optionDict} from "/@/const/dict";

// 定义变量内容
const editCsRecordRef = ref<InstanceType<typeof EditCsRecord>>();

const state = reactive({
    loading: false,
    editTitle: '',
    data: [] as Array<EsSmsInteraction>,
    total: 0 as any,
    queryParams: {
        phone: undefined,
        dateRange: [todayDate(), todayDate()],
        pageNum: 1,
        pageSize: 20,
    },
});

// 打开详情页面
const openEditEsSmsInteraction = (row: any) => {
    state.editTitle = '详情';
    editCsRecordRef.value?.openDialog(row, 'show');
};

onMounted(async () => {
});

onUnmounted(() => {
});

// 查询操作
const handleQuery = async () => {
    // 1. 验证手机号
    if (!state.queryParams.phone) {
        return ElMessage.warning('请先输入手机号');
    }

    // 1. 验证日期范围
    if (state.queryParams.dateRange.length === 0) {
        return ElMessage.warning('请先选择日期');
    }

    try {
        state.loading = true;

        // 2. 参数处理（自动过滤空值）
        const params = {
            ...state.queryParams,
        };

        // 3. API请求
        const {data} = await SysEsSmsInteractionApi().queryRecord(params);

        // 4. 响应处理（安全取值）
        state.data = data?.result?.items || [];
        state.total = data?.result?.total || 0;

        // 手机号脱敏
        const reg = /^(\d{3})\d{4}(\d{4})$/;
        state.data.forEach((item) => {
            item.phoneC = item.phone?.replace(reg, `$1${'*'.repeat(4)}$2`);
        })
    } catch (error) {
        ElMessage.error('数据加载失败');
    } finally {
        state.loading = false;
    }
};

// 重置操作
const resetQuery = () => {
    // 1. 批量重置为undefined
    const keepKeys: string[] = ['pageNum', 'pageSize', 'dateRange']; // 声明需要保留的字段
    Object.keys(state.queryParams).forEach(key => {
        if (!keepKeys.includes(key))
            state.queryParams[key] = undefined;
    });
    // 2. 单独处理日期
    state.queryParams.dateRange = [todayDate(), todayDate()];
    state.data = [];
};

// 改变页面容量
const onHandleSizeChange = (val: number) => {
    state.queryParams.pageSize = val;
    handleQuery();
};

// 改变页码序号
const onHandleCurrentChange = (val: number) => {
    state.queryParams.pageNum = val;
    handleQuery();
};

// 鼠标划入电话单元格时
const TransferIn = (row, column, cell, event) => {
    if (column.property == 'phoneC') {
        row.phoneC = row.phone;
        // console.log(row, column, cell, event);
    }
};

// 鼠标移出电话单元格时
const mark = (row, column, cell, event) => {
    if (column.property == 'phoneC') {
        const reg = /^(\d{3})\d{4}(\d{4})$/;
        row.phoneC = row.phoneC.replace(reg, `$1${'*'.repeat(4)}$2`);
    }
};

// 获取运营商标签文本
const getOperatorLabel = (value: number) => {
    const item = optionDict.operatorPlatformDict.find(item => item.value === value)
    return item?.label || '未知'
}

// 获取标签类型
const getOperatorTagType = (value: number) => {
    const item = optionDict.operatorPlatformDict.find(item => item.value === value)
    return item?.type || 'danger'
}
</script>

<style scoped lang='scss'>
/* 基础样式 */
.date-picker {
    width: 100%;
    max-width: 350px;
}

/* 移动端专属样式 */
.date-picker.is-mobile {
    max-width: 100%;
}

/* 深度样式穿透 */
:deep(.is-mobile .el-input__wrapper) {
    padding: 12px 15px;
}

/* 媒体查询适配 */
@media screen and (max-width: 768px) {
    :deep(.el-picker-panel) {
        width: 90vw !important;
        left: 5vw !important;
        transform: none !important;
    }

    :deep(.el-date-range-picker__content) {
        flex-direction: column;
    }

    /* 触摸优化 */
    :deep(.el-picker-panel__icon-btn) {
        min-width: 44px;
        min-height: 44px;
    }
}
</style>
